package freedom.soluttion.app.restaurante;


import java.util.ArrayList;
import java.util.HashMap;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import freedom.solution.app.restaurante.service.Conexion;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.Menu;


public class MainActivity extends Activity {
	
	GridView MyGrid;
    private ProgressDialog pDialog;
    String [] mesaNum ;
    String [] mesaId ;
    int [] mesaEstado;
    ArrayList<HashMap<String,String>> mesaList;
    ImageAdapter adapter = null;
	private static final String TAG_ID_MESA="id_mesa";
	private static final String TAG_ID_ESTADO="id_estado";
	private static final String TAG_CAPACIDAD="capacidad";
	private static final String TAG_NUMERO="numero";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mesas_principal);
		mesaList = new ArrayList<HashMap<String,String>>();
		mesaNum= new String [20];
	    mesaId= new String [20];
	    mesaEstado= new int [20];
        adapter = new ImageAdapter(this);
      new asyncmesas().execute(); 
      
      
	}
	
	 
	
	public class ImageAdapter extends BaseAdapter
	{
		Context MyContext;
		
		public ImageAdapter(Context _MyContext)
		{
			MyContext = _MyContext;
		}
		
	
		public int getCount() 
		{
		return	mesaList.size();
		}

		
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			((GridView)parent).setNumColumns(GridView.AUTO_FIT);
			View MyView = convertView;
			
			if ( convertView == null )
			{
				LayoutInflater li = getLayoutInflater();
				MyView = li.inflate(R.layout.mesa, null);
				
				TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text);
				tv.setText("Mesa "+ mesaNum[position] );
				ImageView iv = (ImageView)MyView.findViewById(R.id.grid_item_image);
				if(mesaEstado[position]==2){
				
				iv.setImageResource(R.drawable.table);}
				else
					iv.setImageResource(R.drawable.table2);
					
			}
			
			return MyView;
		}

	
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
	}
	
	
	class asyncmesas extends AsyncTask< String, String, String > {
	   	 
    	String user,pass;
        protected void onPreExecute() {
        	//para el progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Cargando Mesas....");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters
        	Conexion odaocliente=new Conexion();
    		odaocliente.ObtenerMesas();
    		
    		SoapObject request = new SoapObject(odaocliente.NAMESPACE, odaocliente.METHOD_NAME);

    		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    		envelope.dotNet = true;

    		envelope.setOutputSoapObject(request);
    		
    		HttpTransportSE transporte = new HttpTransportSE(odaocliente.URL);

    		try 
    		{
    			transporte.call(odaocliente.SOAP_ACTION, envelope);

    			SoapObject resSoap =(SoapObject)envelope.getResponse();
    			
    			String[] mesas = new String[resSoap.getPropertyCount()];
    			
    			for (int i = 0; i < mesas.length; i++) 
    			{
    		           SoapObject ic = (SoapObject)resSoap.getProperty(i);
    		            
    		         
    		           String id_mesa = ic.getProperty(0).toString();
    		           String id_estado= ic.getProperty(1).toString();
    		           String capacidad = ic.getProperty(2).toString();
    		           String numero=ic.getProperty(3).toString();
    		           HashMap<String, String> map = new HashMap<String, String>();
    					
    					 map.put(TAG_ID_MESA, id_mesa);
                         map.put(TAG_ID_ESTADO, id_estado);
                         map.put(TAG_CAPACIDAD, capacidad);
                         map.put(TAG_NUMERO, numero);
    			
    				    mesaNum[i]=numero;
    					mesaId[i]=id_mesa;
    					mesaEstado[i]=Integer.parseInt(id_estado);
    					mesaList.add(map);
    		    }
    		
    		    
    		        
    			
    		} 
    		catch (Exception e) 
    		{
    			//Toast.makeText(this, "No existe categorias", Toast.LENGTH_LONG).show();
    		} 
            return null;
        }
       
		/*Una vez terminado doInBackground segun lo que halla ocurrido 
		pasamos a la sig. activity
		o mostramos error*/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all albums
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                	
               
                 
                	 MyGrid = (GridView)findViewById(R.id.mesas_principal);
                	  MyGrid.setAdapter(adapter);
                	 MyGrid.setOnItemClickListener(new OnItemClickListener() {
                          public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                              //Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
                        		Intent i=new Intent(getApplicationContext(), DetallePedidoActivity.class);
                        		String id_mesaa=mesaId[position];
                        		 i.putExtra("id_mesa", id_mesaa);  
                    				startActivity(i); 
                          }
                      });
                }
            });
 
        }
	}
	
	
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_principal, menu);
        
        return true;
    }
    
	
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.mnu_Bebidas:
     
            return true;
        case R.id.mnu_Menu:
        
            return true;
        case R.id.mnu_EnviarOrden:

            return true;
        case R.id.mnu_Pagar:
      
            return true;
        case R.id.mnu_UnirMesas:
        
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
}